import React, { useMemo } from 'react';
import { Chart as ChartJS, ArcElement, Tooltip, Legend, type ChartOptions } from 'chart.js';
import { Doughnut } from 'react-chartjs-2';
import type { TransactionRead } from '../types';
import Card from './ui/Card';

ChartJS.register(ArcElement, Tooltip, Legend);

interface StatsViewProps {
  transactions: TransactionRead[];
  currencyCode: string;
}

const COLORS = [
  '#2dd4bf', '#38bdf8', '#818cf8', '#fb7185', '#facc15', 
  '#4ade80', '#a78bfa', '#f87171', '#fbbf24', '#a3e635'
];

const StatsView: React.FC<StatsViewProps> = ({ transactions, currencyCode }) => {

  const expenseData = useMemo(() => {
    const categoryTotals: { [key: string]: number } = {};
    
    transactions.forEach(tx => {
      tx.attributes.transactions.forEach(split => {
        if (split.type === 'withdrawal' && split.category_name) {
          const amount = parseFloat(split.amount);
          categoryTotals[split.category_name] = (categoryTotals[split.category_name] || 0) + amount;
        }
      });
    });

    const sortedCategories = Object.entries(categoryTotals)
      .sort(([, a], [, b]) => b - a);

    return {
      labels: sortedCategories.map(([name]) => name),
      data: sortedCategories.map(([, total]) => total),
    };
  }, [transactions]);

  if (expenseData.data.length === 0) {
    return (
        <section>
            <h2 className="text-lg font-semibold text-slate-300 mb-3">支出分类统计</h2>
            <Card className="text-center text-slate-500 py-16">
                <p>没有可供显示的带分类的支出数据。</p>
            </Card>
        </section>
    );
  }

  const chartData = {
    labels: expenseData.labels,
    datasets: [{
      data: expenseData.data,
      backgroundColor: COLORS,
      borderColor: '#1e293b', // bg-slate-800
      borderWidth: 2,
      hoverOffset: 8,
    }],
  };
  
  const chartOptions: ChartOptions<'doughnut'> = {
    responsive: true,
    maintainAspectRatio: false,
    cutout: '70%',
    plugins: {
      legend: {
        display: false,
      },
      tooltip: {
        backgroundColor: '#334155', // bg-slate-700
        titleFont: { size: 14, weight: 'bold' },
        bodyFont: { size: 12 },
        padding: 10,
        cornerRadius: 8,
        callbacks: {
          label: (context: any) => {
            const label = context.label || '';
            const value = context.raw || 0;
            const formattedValue = new Intl.NumberFormat('zh-CN', { style: 'currency', currency: currencyCode }).format(value);
            return `${label}: ${formattedValue}`;
          },
        },
      },
    },
  };

  return (
    <section>
      <h2 className="text-lg font-semibold text-slate-300 mb-3">支出分类统计</h2>
      <Card>
        <div className="h-64 w-full flex justify-center items-center p-4">
          <Doughnut data={chartData} options={chartOptions} />
        </div>
      </Card>
      <div className="mt-4 space-y-2">
        {expenseData.labels.map((label, index) => (
          <div key={label} className="flex items-center justify-between text-sm bg-slate-800/50 p-3 rounded-lg">
            <div className="flex items-center">
              <span className="w-3 h-3 rounded-full mr-3" style={{ backgroundColor: COLORS[index % COLORS.length] }}></span>
              <span className="text-slate-300">{label}</span>
            </div>
            <span className="font-semibold text-slate-100">
              {new Intl.NumberFormat('zh-CN', { style: 'currency', currency: currencyCode }).format(expenseData.data[index])}
            </span>
          </div>
        ))}
      </div>
    </section>
  );
};

export default StatsView;